package com.miot.domain.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.util.LinkedList;
import java.util.List;

/**
 * @Author: zhangyanbin
 * @Date: 2019/1/4 17:50
 * @Version 1.0
 */
public class ControlUnitUtil {
    public static final String GET_METHOD = "GET";
    public static final String POST_METHOD = "POST";
    public static final String URI = "https://bridge.io.mi.com";
    public static final String CREATE_METHOD = "create";
    public static final String EDIT_METHOD = "edit";
    /**
     * echo测试 POST
     */
    public static final String MI_ECHO_TEST = "/bridge/s2s/echo";
    /**
     * 给group id， auth unit id，发送绑定手机号码的短信 POST
     */
    public static final String MI_BIND_PHONE_SMS = "/bridge/s2s/bindphonesms";
    /**
     * 给group id, auth unit id, 设置接收bindkey的手机号 POST
     */
    public static final String MI_BIND_PHONE = "/bridge/s2s/bindphone";
    /**
     * 通过group id， auth unit id, 给手机号发送bindkey POST
     */
    public static final String MI_BIND_KEY_SMS = "/bridge/s2s/bindkeysms";
    /**
     * 通过group id， auth unit id，生成一个control unit POST
     */
    public static final String MI_CONTROL_UNIT = "/bridge/s2s/controlunit";
    /**
     * 通过group id， auth unit id， 获取所有的control units GET
     */
    public static final String MI_CONTROL_UNIT_LIST = "/bridge/s2s/controlunits";
    /**
     * 禁止设备Reset POST
     */
    public static final String MI_DISABLE_RESET = "/bridge/s2s/disablereset";
    /**
     * 获取设备Reset状态 GET
     */
    public static final String MI_GET_DISABLE_RESET = "/bridge/s2s/getdisablereset";
    /**
     * RPC GET
     */
    public static final String MI_RPC = "/bridge/s2s/rpc";
    /**
     * 设置group管理员 GET
     */
    public static final String MI_SET_MGR = "/bridge/s2s/setmgr";
    /**
     * 删除group管理员 GET
     */
    public static final String MI_DELETE_MGR = "/bridge/s2s/delmgr";
    /**
     * 检查小爱升级 GET
     */
    public static final String MI_CHECK_OTA = "/bridge/controlunit/checkOTA";
    /**
     * 推送小爱升级 POST
     */
    public static final String MI_PUSH_OTA = "/bridge/controlunit/pushOTA";
    /**
     * 获取parternerId(bind_id) GET
     */
    public static final String MI_GET_PARTERNERID = "/bridge/controlunit/getParternerId";

    /**
     * 获取设备意图 GET
     */
    public static final String MI_DEVICE_INTENTION = "bridge/s2s/skill/devintention";
    /**
     * 获取场景意图 GET
     */
    public static final String MI_SCENE_INTENTION = "/bridge/s2s/skill/sceneintention";


    private static final Long groupId = 1218L;
    private static final Long authUnitId = 17309038516633600L;
    private static final String privateKey = "MEECAQAwEwYHKoZIzj0CAQYIKoZIzj0DAQcEJzAlAgEBBCA96lBvNVypEGE7rNvwrQCXY2rbLcBXXfHALqVsVdsPmA";
    private static byte[] publicKey = Base64.decodeBase64(
            "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE27mFHWWKKZJjsuG5lKFBl6KEgnHLZU2T24A-ypDokpRL5BN9bQPWJGkMh9WZON8rd6kSVJSVuU24jiveQ22VAw");

    public ControlUnitUtil() {
    }

    protected static Logger logger = LoggerFactory.getLogger(ControlUnitUtil.class);


    public static List<NameValuePair> createParams(String method, String uri, String data) {
        String nonceStr = System.currentTimeMillis() + "";
        List<NameValuePair> params = new LinkedList<>();
        params.add(new BasicNameValuePair("_nonce", nonceStr));
        params.add(new BasicNameValuePair("_groupId", groupId + ""));
        params.add(new BasicNameValuePair("_authUnitId", authUnitId + ""));
        params.add(new BasicNameValuePair("_data", data));
        StringBuilder toSignTextBuilder = new StringBuilder();
        toSignTextBuilder.append(method).append("&").append(uri).append("&").append(data).append("&").append(nonceStr);
        String toSignText = toSignTextBuilder.toString();
        String sign = ECDSAUtil.signWithStr(toSignText.getBytes(), privateKey);
        params.add(new BasicNameValuePair("_signature", sign));
        return params;
    }

    /**
     * 解析小米返回的ControlUnitId
     *
     * @return
     */
    public static Long getControlUnitId() {
        try {
            String url = ControlUnitUtil.URI + ControlUnitUtil.MI_CONTROL_UNIT;
            JSONObject dataValueJson = new JSONObject();
            List<NameValuePair> params = createParams(ControlUnitUtil.POST_METHOD, ControlUnitUtil.MI_CONTROL_UNIT, dataValueJson.toString());
            String postResult = HttpUtils.sendPost(url, params);
            if (StringUtils.isEmpty(postResult)) {
                return null;
            }
            Long controlUnitId = JSONObject.parseObject(postResult).getJSONObject("data").getLong("controlUnitId");
            return controlUnitId;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * echo测试 主要是给验证服务器之间的签名是否合法而准备
     *
     * @return
     */
    public static void echo() {
        try {
            String url = ControlUnitUtil.URI + ControlUnitUtil.MI_ECHO_TEST;
            JSONObject dataValueJson = new JSONObject();
            List<NameValuePair> params = createParams(ControlUnitUtil.POST_METHOD, ControlUnitUtil.MI_ECHO_TEST, dataValueJson.toString());
            String postResult = HttpUtils.sendPost(url, params);
            System.out.println(postResult);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }





    /**
     * 获取列表的公共方法
     *
     * @param controlUnitId
     * @param url
     * @param uri
     * @param method
     * @return
     */
    public static JSONArray getListByControlUnitId(long controlUnitId, String url, String uri, String method) {
        JSONObject dataValueJson = new JSONObject();
        if ("getDeviceList".equalsIgnoreCase(method)) {
            dataValueJson.put("controlUnitId", controlUnitId);
            dataValueJson.put("compact", false);
        } else {
            dataValueJson.put("controlUnitId", controlUnitId);
        }
        List<NameValuePair> params = createParams(ControlUnitUtil.GET_METHOD, uri, dataValueJson.toString());
        String postResult = HttpUtils.sendGet(url, params, null);
        if (postResult == null) {
            return new JSONArray();
        }
        String responseBody = JSONObject.parseObject(postResult).getJSONObject("data").getString("responseBody");
        byte[] bytes = Base64.decodeBase64(responseBody);
        String skillListStr = new String(bytes);
        System.out.println(skillListStr);
        JSONArray skillArray = JSONObject.parseObject(skillListStr).getJSONArray("devices");
        return skillArray;
    }
}
